<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            //2 1 5 6 2 3
            /* 
            stack [0 2 1 5 6 2 3]
            当前元素比栈顶元素大，全部入栈
            遇到小，栈顶元素 6 出栈。计算以6为高度的最大矩形 宽度就是用当前i下标-剩下栈顶元素下标-1

            height[0,2,1,5,6,2,3,0]
            
            i==0:heights[i]=0,stack:[0]
            i==1:height[1]=2  stack:[0,1]
            i==2:height[2]=1  height[i]<height[stack[stack.length-1]] 出栈 stack:[0] maxArea=2*(2-0-1),stack:[0,2]
            i==3:height[3]=5  stack:[0,2,3]
            i==4 height[4]=6  stack:[0,2,3,4]
            i==5 height[5]=2  出栈：stack[0,2,3]  maxArea=6*(5-3-1)  
                 继续比较栈顶  继续出栈 stack[0,2]  maxArea=height[3]*(5-2-1) =10
                
            可以发现，它每次都是取出顶部元素作为高，然后用i-剩下栈顶元素-1作为宽，至于额外-1是因为height中前后多加了0

            
            */
            var largestRectangleArea = function (heights) {
                let maxArea = 0
                let stack = []
                heights = [0, ...heights, 0]
                for (let i = 0; i < heights.length; i++) {
                    //栈顶元素下标
                    //循环判断，当前元素小于栈顶元素
                    while (heights[i] < heights[stack[stack.length - 1]]) {
                        const stackTopIndex = stack.pop()
                        maxArea = Math.max(maxArea, heights[stackTopIndex] * (i - stack[stack.length - 1] - 1))
                    }
                    stack.push(i)
                }
                return maxArea
            }
            largestRectangleArea([2, 1, 5, 6, 2, 3])
        </script>
    </body>
</html>
